package servidor.bancoServidor;

import java.util.ArrayList;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import servidor.modelo.Extrato;

public class MandaEmail {
	private static final String SMTP_HOST_NAME = "smtp.gmail.com";
	private static final String SMTP_PORT = "465";

	// Usado pela main comentada para testar o código
	// private static final String[] sendTo = { "guibruzzi@gmail.com",
	// "fferman1@gmail.com" };
	// private static final String emailSubjectTxt = "A test from gmail";
	// private static final String emailMsgTxt =
	// "Isso é um teste da classe da mandar email do projeto de comp2.";
	private static final String emailFromAddress = "BancoComp2@gmail.com";

	private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

	// Main para testar o código
	// public static void main(String args[]) throws Exception {
	//
	// Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
	//
	// new MandaEmail().sendSSLMessage(sendTo, emailSubjectTxt, emailMsgTxt,
	// emailFromAddress);
	// System.out.println("Sucessfully Sent mail to All Users");
	// }
	private void sendSSLMessage(String recipients[], String subject,
			String message, String from, boolean textAsHtml)
			throws MessagingException {
		boolean debug = false;

		Properties props = new Properties();
		props.put("mail.smtp.host", SMTP_HOST_NAME);
		props.put("mail.smtp.auth", "true");
		props.put("mail.debug", "true");
		props.put("mail.smtp.port", SMTP_PORT);
		props.put("mail.smtp.socketFactory.port", SMTP_PORT);
		props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
		props.put("mail.smtp.socketFactory.fallback", "false");

		Session session = Session.getDefaultInstance(props,
				new javax.mail.Authenticator() {

					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication("BancoComp2",
								"123BancoComp2");
					}
				});

		session.setDebug(debug);

		Message msg = new MimeMessage(session);
		InternetAddress addressFrom = new InternetAddress(from);
		msg.setFrom(addressFrom);

		InternetAddress[] addressTo = new InternetAddress[recipients.length];
		for (int i = 0; i < recipients.length; i++) {
			addressTo[i] = new InternetAddress(recipients[i]);
		}
		msg.setRecipients(Message.RecipientType.TO, addressTo);

		// Setting the Subject and Content Type
		msg.setSubject(subject);

		msg.setContent(message, (textAsHtml) ? "text/html" : "text/plain");
		Transport.send(msg);
	}

	public void sendSSLMessage(String recipients[], String subject,
			String message) throws MessagingException {
		sendSSLMessage(recipients, subject, message, emailFromAddress);
	}

	public void sendSSLMessage(String recipients[], String subject,
			String message, String from) throws MessagingException {
		sendSSLMessage(recipients, subject, message, from, false);
	}

	public void sendSSLMessageHtml(String recipients[], String subject,
			String message) throws MessagingException {
		sendSSLMessageHtml(recipients, subject, message, emailFromAddress);
	}

	public void sendSSLMessageHtml(String recipients[], String subject,
			String message, String from) throws MessagingException {
		sendSSLMessage(recipients, subject, message, from, true);
	}

	private void addToBuilder(StringBuilder sb, String s) {
		sb.append(String.format("%s\n", s));
	}

	private String mandaExtratos(ArrayList<Extrato> extratos)
			throws MessagingException {
		StringBuilder sb = new StringBuilder();
		int contaId = extratos.get(0).getConta().getID();
		// addToBuilder(sb,
		// "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />");
		addToBuilder(sb,
				"<table border=\"0\" cellspacing=\"3\" cellpadding=\"3\" >");
		addToBuilder(sb, "<thead>");
		addToBuilder(
				sb,
				"<tr><td colspan=\"3\" align=\"center\" bgcolor=\"#B3D9EC\" style=\"font-family: Monotype Corsiva, arial, helvetica, serif; font-weight:bold; font-size:60px; color:white;\">Banco Carioca</td></tr>");
		addToBuilder(
				sb,
				"<tr bgcolor=\"#DBEEF7\" style=\"font-family: arial, helvetica, serif; font-size:20px;\"><td colspan=\"3\" align=\"center\">Extrato da conta "
						+ contaId + "</td></tr>");
		addToBuilder(sb, "<tr  bgcolor=\"#DBEEF7\">");
		addToBuilder(sb, "<th style=\"width:200px;\">Data</th>");
		addToBuilder(sb, "<th>Operacao</th>");
		addToBuilder(sb, "<th style=\"width:200px;\">Movimentacao</th>");
		addToBuilder(sb, "</tr>");
		addToBuilder(sb, "</thead>");

		addToBuilder(sb, "<tbody>");
		for (Extrato extrato : extratos) {
			sb.append("<tr  bgcolor=\"#DBEEF7\">");
			sb
					.append("<td align=\"center\" valign=\"middle\" style=\"color:blue\">"
							+ extrato.getData() + "</td>");
			sb.append("<td align=\"center\" valign=\"middle\">"
					+ extrato.getOperacao() + "</td>");
			String color = (extrato.getMovimentacao().contains("+")) ? "green"
					: "red";
			sb.append("<td align=\"center\" valign=\"middle\" style=\"color:"
					+ color + "\">" + extrato.getMovimentacao() + "</td>");
			sb.append("</tr>");
		}
		addToBuilder(sb, "</tbody>");
		addToBuilder(sb, "</table>");

		return sb.toString();
	}

	public void sendSSLMessageHtmlExtratos(String recipients[], String subject,
			ArrayList<Extrato> extratos) throws MessagingException {
		sendSSLMessageHtml(recipients, subject, mandaExtratos(extratos));
	}
}
